import 'package:flutter/material.dart';
import 'package:hi_base/color.dart';
import 'package:smart/navigator/hi_navigator.dart';
import 'package:smart/page/favorite_page.dart';
import 'package:smart/page/home_page.dart';
import 'package:smart/page/profile_page.dart';
import 'package:smart/page/rank_page.dart';

class BottomNavigator extends StatefulWidget {
  const BottomNavigator({super.key});

  @override
  State<BottomNavigator> createState() => _BottomNavigatorState();
}

class _BottomNavigatorState extends State<BottomNavigator> {
  final _defaultColor = Colors.grey;
  final _activeColor = red;
  int _currentIndex = 0;
  static int initialPage = 0;
  final PageController _controller = PageController(initialPage: initialPage);
  List<Widget>? _pages;
  bool _hasBuild = false;

  @override
  Widget build(BuildContext context) {
    _pages = [
      HomePage(onJumpTo: (index) => _onJumpTo(index, pageChange: false)),
      RankingPage(),
      FavoritePage(),
      ProfilePage()
    ];
    if (!_hasBuild) {
      //页面第一次打开时候通知打开的是哪个tab
      HiNavigator.getInstance()
          .onBottomTabChange(initialPage, _pages![initialPage]);
      _hasBuild = true;
    }

    return Scaffold(
        body: PageView(
            controller: _controller,
            children: _pages!,
            onPageChanged: (index) => _onJumpTo(index, pageChange: true),
            physics: NeverScrollableScrollPhysics()),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: (index) => _onJumpTo(index),
          selectedItemColor: _activeColor,
          type: BottomNavigationBarType.fixed, // 不让点击底部导航，底部样动画改变。
          items: [
            _bottomItem('首页', Icons.home, 0),
            _bottomItem('排行', Icons.local_fire_department, 1),
            _bottomItem('收藏', Icons.favorite, 2),
            _bottomItem('我的', Icons.live_tv, 3)
          ],
        ));
  }

  _bottomItem(String title, IconData icon, int index) {
    return BottomNavigationBarItem(
        icon: Icon(icon, color: _defaultColor),
        activeIcon: Icon(icon, color: _activeColor),
        label: title);
  }

  void _onJumpTo(int index, {pageChange = false}) {
    // 让PageView 展示对应的 tab
    if (!pageChange) {
      //让P阿哥View 展示对应的tab
      _controller.jumpToPage(index);
    } else {
      HiNavigator.getInstance().onBottomTabChange(index, _pages![index]);
    }

    setState(() {
      //控制选中的第几个tab
      _currentIndex = index;
    });
  }
}
